package org.otherworld.frame.textwriter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;

public class ActionLoadDocument implements ActionListener{
	private JTextArea area;
	private StringBuilder fileText;
	public ActionLoadDocument(JTextArea area) {
		this.area = area;
	}
	
	public void actionPerformed(ActionEvent e) {
		final JFileChooser fileChooser = new JFileChooser();
		int returnVal = fileChooser.showOpenDialog(area);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			File file = fileChooser.getSelectedFile();
			try {
				this.fileText = this.getFileContents(file);
				area.setText(this.fileText.toString());
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}
	}
	
	private StringBuilder getFileContents(File file) throws Exception{
		BufferedReader reader = new BufferedReader(new FileReader(file));
		String line = "";
		StringBuilder text = new StringBuilder();
		while ((line = reader.readLine())!=null) {
			text.append(line);
			text.append(System.getProperty("line.separator"));
		}	
		reader.close();
		return text;
	}

}
